package com.magic.auth;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.magic.result.Result;

/**
 * ClassName: TokenFilter <br/>
 * token认证过滤器 date: 2018年10月26日 上午10:05:27 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Component
public class TokenFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

	public static final String AUTH_KEY = "Authorization";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		// 允许进行跨域的主机ip（动态配置具体允许的域名和IP）
		rep.setHeader("Access-Control-Allow-Origin", "*");
		// 允许的访问方法
		rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
		// Access-Control-Max-Age 用于 CORS 相关配置的缓存
		rep.setHeader("Access-Control-Max-Age", "3600");
		rep.setHeader("Access-Control-Allow-Headers", "*");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		String token = req.getHeader(AUTH_KEY);
		Result result = new Result();
		boolean isFilter = false;
		String method = ((HttpServletRequest) request).getMethod();
		if (method.equals("OPTIONS")) {
			rep.setStatus(HttpServletResponse.SC_OK);
		} else {
			if (null == token || token.isEmpty()) {
				result.setCode(Result.AUTH_ERROR);
				result.setMessage("no Authorization");
			} else {
				try {
					if (TokenUtil.checkToken(token)) {
						isFilter = true;
					} else {
						result.setCode(Result.AUTH_ERROR);
						result.setMessage("Authorization is not valid");
					}
				} catch (Exception e) {
					logger.error("TokenFilter.doFilter()方法异常{}:{}");
				}
			}
			if (result.getCode() == Result.AUTH_ERROR) {// 验证失败
				PrintWriter writer = null;
				OutputStreamWriter osw = null;
				try {
					osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
					writer = new PrintWriter(osw, true);
					String jsonStr = JSON.toJSONString(result);
					writer.write(jsonStr);
					writer.flush();
					writer.close();
					osw.close();
				} catch (UnsupportedEncodingException e) {
					logger.error("过滤器返回信息失败:" + e.getMessage(), e);
				} catch (IOException e) {
					logger.error("过滤器返回信息失败:" + e.getMessage(), e);
				} finally {
					if (null != writer) {
						writer.close();
					}
					if (null != osw) {
						osw.close();
					}
				}
				return;
			}
			if (isFilter) {
				chain.doFilter(request, response);
			}
		}
	}

	@Override
	public void destroy() {

	}

}
